package com.atguigu.tingshu.cdc.handler;

import com.atguigu.tingshu.cdc.entity.CdcEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import top.javatool.canal.client.annotation.CanalTable;
import top.javatool.canal.client.handler.EntryHandler;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @author codingyz
 * @Description
 * @date 2025/3/25 19:05
 * @Version 1.0
 */
@Component
@CanalTable("album_info")
@Slf4j
public class CdcEntityHandler implements EntryHandler<CdcEntity> {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public void insert(CdcEntity cdcEntity) {
        // 数据新增时回调
        log.info("canal客户端监听到album_info数据新增{}", cdcEntity.getId());

    }

    @Override
    public void update(CdcEntity before, CdcEntity after) {
        // 数据更新时回调
        log.info("canal客户端监听到album_info数据更新{}-->{}", before.getId(), after.getId());
        ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(2);
        try {
            // 延迟删除
            scheduledExecutorService.schedule(() -> {
                redisTemplate.delete("cache:info:" + after.getId());
            }, 200, TimeUnit.MILLISECONDS);
//            redisTemplate.delete("cache:info:" + before.getId());
        } catch (Exception e) {
            // todo mq重试
            log.error("更新MySQL数据时删除缓存数据出异常,重试中,原因是{}", e.getMessage());
        } finally {
            scheduledExecutorService.shutdown();
        }
    }

    @Override
    public void delete(CdcEntity cdcEntity) {
        // 数据删除时回调
        log.info("canal客户端监听到album_info数据删除{}", cdcEntity.getId());
        ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(2);
        try {
            scheduledExecutorService.schedule(() -> {
                redisTemplate.delete("cache:info:" + cdcEntity.getId());
            }, 200, TimeUnit.MILLISECONDS);
//            redisTemplate.delete("cache:info:" + cdcEntity.getId());
        } catch (Exception e) {
            // todo mq重试
            log.error("删除MySQL数据时删除缓存数据出异常,重试中,原因是{}", e.getMessage());
        } finally {
            scheduledExecutorService.shutdown();
        }
    }
}
